package cn.ingrun.cloud_disk.auth;

import cn.ingrun.cloud_disk.auth.authService.AuthService;
import cn.ingrun.cloud_disk.model.User;
import cn.ingrun.cloud_disk.utils.StringUtil;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;

@Aspect
@Component
public class LoginAuthAspect {

//    Logger logger = Logger.getLogger(this.getClass());
    private final static Logger logger = LoggerFactory.getLogger(LoginAuthAspect.class);

    private AuthService authService;

    @Autowired
    public void setAuthService(AuthService authService) {
        this.authService = authService;
    }

    @Pointcut("@annotation(LoginAuth)")
    public void loginAuth(){
    }

    @Before("loginAuth()")
    public void doBefore() throws Exception {
        logger.info("check user login");

        //获取当前http请求
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null){
            throw new Exception("attributes is null");
        }
        HttpServletRequest request = attributes.getRequest();

        String token = request.getHeader("Authorization").substring(7);

        logger.info("token:" + token);

        if(StringUtil.isNullOrEmpty(token)){
            throw new Exception("token 不存在或已失效！");
        }
        User user = authService.checkToken(token);
        if (user == null){
            throw new Exception("token 不存在或已失效！");
        }
        logger.info("验证通过");
    }

}
